<?php

namespace Frieza\Modules\SpiderUser\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Member;
use Doraemon\model\Photos;
use Doraemon\model\Spider\SpiderNote as dbSpiderNote;
use Doraemon\service\Spider\SpiderUserList;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Illuminate\Http\Request;

class SpiderNoteController extends Controller
{

    const PAGE_SIZE = 20;
    const MAX_NOTE_SIZE = 10;//每个用户最多显示的动态条数
    const MAX_SHOW_LENGTH = 28;//页面最大显示长度
    public function list(Request $request, Content $content)
    {
        $params = $request->all();
        $params['page'] = $request->input('page', 1);
        $params['per_page'] = $request->input('per_page', self::PAGE_SIZE);
        if(!isset($params['uid'])) {
            $request->merge(['uid'=>$params['uid']]);
        }

        return $content
            ->header('第三方动态管理')
            ->breadcrumb(
                [
                    'text' => '第三方动态列表',
                    'url'  => '/spiderUser/note/list'
                ]
            )
            ->body(self::listAction($params));
    }


    private static function listAction($params = [])
    {
        $data = dbSpiderNote::getNoteListGroupByUser($params, [
            'obj_id',
            'source',
        ]);

        $list = $data['data'];
        $field = ['id', 'uid', 'title', 'remark', 'addtime'];
        $userNoteListMap = [];
        if (!empty($list)) {
            foreach ($list as &$row) {
                //根据obj_id和source获取最新的10条动态
                if (empty($userNoteListMap) || !isset($userNoteListMap[$row['obj_id']])) {
                    $noteList = Photos::getLastPhotosByUid($row['obj_id'], $field, 1, self::MAX_NOTE_SIZE);
                } else {
                    $noteList = $userNoteListMap[$row['obj_id']];
                }
                $groupParams = [
                    'obj_id' => $row['obj_id'],
                    'source' => $row['source'],
                ];
                $otherNoteList = dbSpiderNote::getNoteList($groupParams);
                $row['otherNotes'] = $otherNoteList['data'] ?? [];
                $row['notes'] = $noteList;
            }
        }

        $gridModel = new pGridDataModel($list, $data['total'], [
            'perPage' => $params['per_page'],
        ]);


        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->paginate(self::PAGE_SIZE);

            // 筛选项
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('uid', '用户ID')->placeholder('请输入用户ID');
                });
                $filter->date('pubTime', '发布日期');
            });
            $grid->column('uid', '用户ID')->display(function () {
                return $this->obj_id;
            });
            $grid->column('nickName', '用户昵称')->display(function () {
               return  Member::getNickByUid($this->obj_id);
            });
            $grid->column('notes', '最新动态')->display(function () {
                $html = '';
                foreach ($this->notes as $item) {
                    if (empty($item['title']) && empty($item['remark'])) {
                        continue;
                    }
                    $showContent = $item['title'] ?: $item['remark'];
                    $html .= date('Y-m-d', $item['addtime']) . str_repeat('&nbsp;', 5) . self::getPageShowContent($showContent);
                    $html .= '<br/>';
                }
                return $html;
            });
            $grid->column('source', '来源')->display(function () {
                return SpiderUserList::SOURCE_MAP[$this->source] ?? '';
            });
            $grid->column('otherNotes', '第三方最新动态')->display(function () {
                $html = '';
                foreach ($this->otherNotes as $item) {
                    $showContent = $item['other_note_title'] ?: $item['other_note_content'];
                    $html .= date('Y-m-d', strtotime($item['other_note_pub_time'])) . str_repeat('&nbsp;', 5) . self::getPageShowContent($showContent);
                    $html .= '<br/>';
                }
                return $html;
            });
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('<a href="'.url("admin/spiderUser/note/" . $actions->row->obj_id . "/detail").'" class="fa fa-info-circle">查看</a>');
            });
        });

        return $listGrid;
    }

    public function detail(Content $content, $uid = 0) {
        $content
            ->title('第三方动态详情')
            ->breadcrumb(
                [
                    'text' => '第三方动态列表',
                    'url'  => '/spiderUser/note/list'
                ]
            )
            ->row(function (Row $row) use ($uid){

                $row->column(12, function (Column $column) use ($uid) {
                    $column->append(self::showNoteList($uid));
                });
            });
        foreach (SpiderUserList::SOURCE_MAP as $source => $sourceName) {
            $content->row(function (Row $row) use ($uid, $source, $sourceName){
                $row->column(12, function (Column $column) use ($uid, $source, $sourceName) {
                    $column->append(self::showOtherNoteList($uid, $source, $sourceName));
                });
            });
        }

        return $content;
    }

    /**
     * 根据用户ID显示好好住自有的最新动态
     * @param $uid
     * @return View|string
     */
    private static function showNoteList($uid) {
        $field = ['id', 'uid', 'title', 'remark', 'addtime'];
        $noteList = Photos::getLastPhotosByUid($uid, $field, 1, self::MAX_NOTE_SIZE);
        $result = [
            'tableHeader' => '好好住最新动态',
            'rowWidth' => ['pub_time' => 2, 'title' => 4, 'remark' => 6],
            'list' => [],
        ];
        if (empty($noteList)) {
            return view("spiderUser::multiple-column-table", $result);
        }
        $list = [];
        foreach ($noteList as $row) {
            $list[] = [
                'pub_time' => date('Y-m-d', $row['addtime']),
                'title' => $row['title'],
                'remark' => self::getPageShowContent($row['remark'], 100, false),
            ];
        }
        $result['list'] = $list;
        $result['titleList'] = ['pub_time' => '发布日期', 'title' => '标题', 'remark' => '内容'];
        return view("spiderUser::multiple-column-table", $result);
    }

    private static function showOtherNoteList($uid, $source, $sourceName) {
        $field = ['id', 'obj_id', 'other_note_title', 'other_note_content', 'other_note_pub_time'];
        $noteList = dbSpiderNote::getNoteList([
            'uid' => $uid,
            'source' => $source,
        ], $field, 1, self::MAX_NOTE_SIZE);
        if (empty($noteList) || empty($noteList['data'])) {
            return '';
        }
        $list = [];
        $noteList = $noteList['data'];
        foreach ($noteList as $row) {
            $list[] = [
                'pub_time' => date('Y-m-d', strtotime($row['other_note_pub_time'])),
                'title' => $row['other_note_title'],
                'remark' => self::getPageShowContent($row['other_note_content'], 100, false),
            ];
        }

        $titleList = ['pub_time' => '发布日期', 'title' => '标题', 'remark' => '内容'];
        return view("spiderUser::multiple-column-table", [
            'tableHeader' => $sourceName . '最新动态',
            'titleList' => $titleList,
            'list' => $list,
            'rowWidth' => ['pub_time' => 2, 'title' => 4, 'remark' => 6],
        ]);
    }

    private function editAction($uid) {
        $field = ['id', 'uid', 'title', 'remark', 'addtime'];
        $noteList = Photos::getLastPhotosByUid($uid, $field, 1, self::MAX_NOTE_SIZE);

        $gridModel = new pGridDataModel($noteList);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableTools();
            $grid->disableDefineEmptyPage();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableActions();
            $grid->disablePagination();

            $grid->column('noteDetail', '好好住最新动态');
            $grid->column('addtime', '发布日期')->display(function () {
                return date('Y-m-d', $this->addtime);
            });
            $grid->column('title', '标题')->display(function () {
                return self::getPageShowContent($this->title, 30);
            });
            $grid->column('remark', '内容')->display(function () {
                return self::getPageShowContent($this->remark, 100);
            });
        });

        return $listGrid;
    }

    /**
     * 页面展示内容（根据内容长短适当省略）
     * @param string $showContent
     * @params int $length
     * @params bool $addStyle 是否加样式
     * @return string
     */
    private static function getPageShowContent($showContent, $length = self::MAX_SHOW_LENGTH, $addStyle = true) {
        if ($addStyle) {
            return '<span title="'.$showContent.'">'.(mb_strlen($showContent) > $length ? mb_substr($showContent, 0, $length) . '...' : $showContent) .'</span>';
        } else {
            return (mb_strlen($showContent) > $length ? mb_substr($showContent, 0, $length) . '...' : $showContent);
        }
    }
}